package com.lzq.course.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzq.course.server.domain.Teacher;
import com.lzq.course.server.domain.TeacherExample;
import com.lzq.course.server.dto.ResponseDto;
import com.lzq.course.server.dto.TeacherDto;
import com.lzq.course.server.dto.PageDto;
import com.lzq.course.server.mapper.TeacherMapper;
import com.lzq.course.server.util.CopyUtil;
import com.lzq.course.server.util.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class TeacherService {

    @Resource
    private TeacherMapper teacherMapper;

    /**
     * example 这个文件很有用
     * 可以帮我们生成where order 查询
     * 不用单独写sql的增删改查
     */
    public void list(PageDto<TeacherDto> pageDto) {
        // 分页查询 页码不是从0开始
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());

        // 排序
        TeacherExample teacherExample = new TeacherExample();

        // 查询
        List<Teacher> teacherList = teacherMapper.selectByExample(teacherExample);

        PageInfo<Teacher> pageInfo = new PageInfo<>(teacherList);
        pageDto.setTotal(pageInfo.getTotal());

        List<TeacherDto> teacherDtoList = CopyUtil.copyList(teacherList, TeacherDto.class);

        pageDto.setList(teacherDtoList);
    }

    /**
     * 保存 修改
     * @param teacherDto
     */
    public void save(TeacherDto teacherDto) {
        //BeanUtils.copyProperties(teacherDto, teacher);
        Teacher copyTeacher = CopyUtil.copy(teacherDto, Teacher.class);

        if (StringUtils.isEmpty(teacherDto.getId())) {
            // 新增
            // 八位的 id
            copyTeacher.setId(UuidUtil.getShortUuid());

            Date now = new Date();

            teacherMapper.insert(copyTeacher);
        } else {
            // 编辑
            teacherMapper.updateByPrimaryKey(copyTeacher);
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {
        teacherMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询所有 老师
     * @return
     */
    public ResponseDto all() {
        ResponseDto responseDto = new ResponseDto();

        List<Teacher> teachers = teacherMapper.selectByExample(null);
        List<TeacherDto> teacherDtos = CopyUtil.copyList(teachers, TeacherDto.class);
        responseDto.setContent(teacherDtos);

        return responseDto;
    }

    /**
     * 查找
     * @param id
     */
    public TeacherDto findById(String id) {
        Teacher teacher = teacherMapper.selectByPrimaryKey(id);
        return CopyUtil.copy(teacher, TeacherDto.class);
    }
}
